package com.itheima.springboot_23_mail.service.impl;

import com.itheima.springboot_23_mail.service.SendMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendMailServiceImpl2 implements SendMailService {

    @Autowired //从配置文件中获取sendmail的配置
    private JavaMailSender javaMailSender;

    private String from="1320910060@qq.com";
    private String to="gaoguangchao@intellicredit.cn";
    private String subject="test主题";
    //private String context="test内容";//这是简单邮件的正文
    private String context="<a href='https://www.baidu.com'>点击有惊喜</a> <img src='http://n.sinaimg.cn/games/transform/547/w485h862/20211103/4d8c-7dc7518209c88a043d115371cf1074bc.png'>";
    //这是正文支持html的正文



    @Override
    public void sendMail() {
        //发送简单邮件
//        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
//        simpleMailMessage.setFrom(from);
//        simpleMailMessage.setTo(to);
//        simpleMailMessage.setSubject(subject);
//        simpleMailMessage.setText(context);
//        javaMailSender.send(simpleMailMessage);

        //发送带附件的邮件
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from+"(来自某某某)");
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(context,true);//这个true表示需要将内容转换成html格式的进行发送

            //添加附件 也可以注释附件,从而不发送附件
            File file1=new File("D:\\U\\test\\gitee\\springboottest\\test13\\springboot_23_mail\\src\\main\\resources\\1.jpg");
            File file2=new File("D:\\U\\test\\gitee\\springboottest\\test13\\springboot_23_mail\\src\\main\\resources\\1.jpg");

            mimeMessageHelper.addAttachment(file1.getName(),file1);
            mimeMessageHelper.addAttachment(file2.getName(),file2);
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
